import md5 from "./md5.js"

const baseUrl = "https://m.xliank.com"

function http({
  url,
  data = {},
  method = "POST",
  isShowLoading = false,
  successCb,
  failCb,
  finishCb,
}) {
  let params = md5(data)
  let token = wx.getStorageSync("xlk_token")
  let uid = wx.getStorageSync("xlk_uid")
  
  if(isShowLoading) {
    wx.showLoading({
      title: '加载中',
    })
  }

  wx.request({
    url: baseUrl + url,
    data: params,
    method: method,
    header: {
      "token":token,
      "uid":uid,
      "edition":"1.3.4",
      "platform":"xinlianka",
      "model":"web"
    },
    success(res) {
      if(isShowLoading) {
        wx.hideLoading()
      }

      if(finishCb) {
        finishCb()
      }

      if(res.statusCode != 200) {
        wx.showLoading({
          title: '请求出错',
          icon:'none'
        })
        setTimeout(function() {
          wx.hideLoading()
        }, 1500)
        return
      }
      if(res.data.code == 200) {
        // TODO 成功返回
        successCb(res.data)
      } else {
        if (failCb) {
          failCb(res.data)
        } else if (res.data.code == 100 || res.data.code == 111) {
          wx.redirectTo({
            url: "/pages/login/index",
          })
        } else if (res.data.code == 112) {
          wx.redirectTo({
            url: '/pages/real/index',
          })
        } else if (res.data.code == 113) {
          if (res.data.data.is_remind == 1) {
            wx.showModal({
              title: res.data.data.title,
              content: res.data.data.str.join(","),
               showCancel: false,
              success(res) {
                console.log(res)
              }
            })
          }
        } else {
          // TODO
          if (res.data) {
            wx.showToast({
              title: res.data.msg,
              icon: "none"
            })
          } else {
            wx.showToast({
              title: "您的网络请求出错了",
              icon: "none"
            })
          }
        }
      }
    }  
  })
}

module.exports = {
  http: http
}